//
//  ShopDetailViewController.m
//  Products_B
//
//  Created by lanou on 16/5/30.
//  Copyright © 2016年 朋学友. All rights reserved.
//

#import "ShopDetailViewController.h"
#import "ShopDetailTableViewCell.h"
#import "HeaderView.h"
#import "SureDingdanViewController.h"
#define kShopDetailUrl @"http://api.izhangchu.com/"

@interface ShopDetailViewController () <UITableViewDataSource,UITableViewDelegate, UIWebViewDelegate> {
    UIView     *_centerView;
    UILabel    *_label;
    UIButton   *_chaButton;
    UIView     *_lineView;
    UIButton   *_jianButton;
    UIButton   *_jiaButton;
    UILabel    *_numLabel;
    UILabel    *_totalRMBLabel;
    UIButton   *_sureButton;
    int         _count;
}

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) ShopDetailTableViewCell *cell;
@property (nonatomic, assign) NSInteger webViewH;
@property (nonatomic, strong) NSMutableArray *imageUrlStringArray;
@property (nonatomic, strong) HeaderView *headerView;
@property (nonatomic, strong) UIView *transprrentView;
@end

@implementation ShopDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _count = 1;
    // Do any additional setup after loading the view.
    _imageUrlStringArray = [NSMutableArray array];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight - 64) style:UITableViewStylePlain];
    _tableView.dataSource = self;
    _tableView.delegate = self;

    [self.view addSubview:_tableView];
    // 注册
    [_tableView registerClass:[ShopDetailTableViewCell class] forCellReuseIdentifier:@"shopDetailTableViewCell"];
    [_tableView registerClass:[UITableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:@"footer"];
    
    _transprrentView = [[UIView alloc] initWithFrame:self.view.bounds];
    _transprrentView.backgroundColor = [UIColor blackColor];
    _transprrentView.alpha = 0.6;
    _transprrentView.hidden = YES;
    [self.view addSubview:_transprrentView];
    
    [self requestData];
}


// NSDictionary *parDic = @{@"methodName":@"CommoditiesView",@"version":@4.2,@"id":@(_id),@"user_id":@1513438,@"_time":@1464678296,@"_signature":@"45ada34d2dd58199ba2d6c94e85b5231"};
- (void)requestData {
    NSDictionary *parDic = @{@"methodName":@"CommoditiesView",@"version":@4.2,@"id":@(_id),@"_time":@1464678296,@"_signature":@"45ada34d2dd58199ba2d6c94e85b5231"};
    [RequestManager requestWithUrl:kShopDetailUrl requestType:RequestTypePOST parDic:parDic finish:^(NSData *data) {
        NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSLog(@" ---- %@",jsonDic);
   
        NSString *string = jsonDic[@"data"][@"commodityDesc"];
        NSRange range1 = [string rangeOfString:@"<pre>"];
        NSRange range2 = [string rangeOfString:@"</pre>"];
        if (range1.location < 200000 && range2.location < 200000) {
            string = [string stringByReplacingCharactersInRange:NSMakeRange(range1.location, range2.location + range2.length - range1.location) withString:@""];
        }
        string = [NSString stringWithFormat:@"<head><style>img{width:100%% !important;}</style></head>%@", string];
        
        // 属性赋值，加载webView的内容
        _cell.webString = string;  // 调用了set方法,set方法中加载了webView
        _cell.webView.delegate = self;
        // 以上两步不要在返回cell的代理方法中去实现，否则会出现死循环
        
        [self.tableView reloadData];
        
        // 装载图片url
        NSArray *imageListArray = jsonDic[@"data"][@"imageList"];
        for (NSDictionary *tempDic in imageListArray) {
            NSString *imageString = tempDic[@"image"];
            [_imageUrlStringArray addObject:imageString];
        }
        // 布局tableVIew的头部控件
        _headerView = [[HeaderView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 10) imageUrlArray:_imageUrlStringArray];
        
        _headerView.salesLabel.text = [NSString stringWithFormat:@"已售:%@",jsonDic[@"data"][@"sales"]];
        _headerView.nameLabel.text = jsonDic[@"data"][@"name"];
        _headerView.priceLabel.text = [NSString stringWithFormat:@"￥%@",jsonDic[@"data"][@"price"]];
        _headerView.streetpriceLabel.text = [NSString stringWithFormat:@"原价:%@",jsonDic[@"data"][@"streetPrice"]];
        NSInteger postage = [jsonDic[@"data"][@"postage"] integerValue];
        NSLog(@" postage = %ld",postage);
        if (postage == 0) {
            _headerView.postLabel.text = @"包邮";
        } else {
            _headerView.postLabel.text = [NSString stringWithFormat:@"运费:%@",jsonDic[@"data"][@"postage"]];
        }
        _headerView.frame = CGRectMake(0, 0, kWidth, _headerView.scrollView.frame.size.height + _headerView.salesLabel.frame.size.height + _headerView.nameLabel.frame.size.height + _headerView.priceLabel.frame.size.height + 40);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            self.tableView.tableHeaderView = _headerView;
            // 请求完数据之后去创建一张View，该view中需要一个总计金额数据
            [self creatView];
            _centerView.hidden = YES;
        });

    } error:^(NSError *error) {
        
    }];
    
}


// 本tableView只有一个cell
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ShopDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"shopDetailTableViewCell" forIndexPath:indexPath];
    _cell = cell;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSLog(@" -- %ld",_webViewH);
    return _webViewH;
}

// webView加载完毕时执行的方法
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    //    让webView执行一个JS命令，JS命令式从参数数字字符串获取到的
    //    注入JS脚本（命令）
    //    [webView stringByEvaluatingJavaScriptFromString:@""];

    CGFloat webViewH = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight;"] floatValue];
    CGRect newFrame = webView.frame;
    newFrame.size.height = webViewH;
    webView.scrollView.bounces = NO;
    webView.frame = newFrame;
    _webViewH = webViewH;
    
    [_tableView reloadData];
}

#pragma mark - push的时候隐藏tabBar
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        self.hidesBottomBarWhenPushed = YES;
    }
    return self;
}

// 区尾
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UITableViewHeaderFooterView *footerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"footer"];
    
    UIButton *buyButton = [UIButton buttonWithType:UIButtonTypeCustom];
    buyButton.frame = CGRectMake(50, 10, kWidth - 100, 30);
    [buyButton setTitle:@"立即购买" forState:UIControlStateNormal];
    buyButton.backgroundColor = [UIColor orangeColor];
    [buyButton addTarget:self action:@selector(buyButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:buyButton];
    return footerView;
}

- (void)buyButtonAction:(UIButton *)button {
    _transprrentView.hidden = NO;
    // 不要在此调用creatView方法，该方法执行一次就够，不需要每次点击button都去创建view,那样损耗性能
    _centerView.hidden = NO;
 
}


- (void)creatView {
    _centerView = [[UIView alloc] initWithFrame:CGRectMake(50, (kHeight - 64 - 50 - 200) / 2, kWidth - 100, 200)];
    _centerView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_centerView];
    
    _label = [[UILabel alloc] initWithFrame:CGRectMake(10, 8, _centerView.frame.size.width / 2, 20)];
    _label.text = @"请选择购买数量";
    _label.font = [UIFont systemFontOfSize:14];
    [_centerView addSubview:_label];
    
    _chaButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _chaButton.frame = CGRectMake(_centerView.frame.size.width - 30, 0, 30, 30);
    [_chaButton setTitle:@"×" forState:UIControlStateNormal];
    _chaButton.alpha = 0.6;
    [_chaButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_chaButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    _chaButton.tag = 101;
    [_centerView addSubview:_chaButton];
    
    _lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 36, _centerView.frame.size.width, 1)];
    _lineView.backgroundColor = [UIColor grayColor];
    _lineView.alpha = 0.5;
    [_centerView addSubview:_lineView];
    
    _jianButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _jianButton.frame = CGRectMake(_label.frame.origin.x, 52, _label.frame.size.width / 2, 50);
    _jianButton.layer.borderWidth = 1;
    [_jianButton setTitle:@"-" forState:UIControlStateNormal];
    [_jianButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_jianButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    _jianButton.tag = 102;
    [_centerView addSubview:_jianButton];
    
    _jiaButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _jiaButton.frame = CGRectMake(_centerView.frame.size.width - 10 - _label.frame.size.width / 2, 52, _label.frame.size.width / 2, 50);
    _jiaButton.layer.borderWidth = 1;
    _jiaButton.layer.borderColor = [UIColor orangeColor].CGColor;
    [_jiaButton setTitle:@"+" forState:UIControlStateNormal];
    [_jiaButton setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    [_jiaButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    _jiaButton.tag = 103;
    [_centerView addSubview:_jiaButton];
    
    _numLabel = [[UILabel alloc] initWithFrame:CGRectMake(_centerView.frame.size.width / 2, _jiaButton.frame.origin.y + 18, 20, 20)];
    _numLabel.text = [NSString stringWithFormat:@"%d",_count];
    _numLabel.font = [UIFont systemFontOfSize:18];
    [_centerView addSubview:_numLabel];
    
    _totalRMBLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, _jianButton.frame.origin.y + _jianButton.frame.size.height + 15, _centerView.frame.size.width - 20, 20)];
    _totalRMBLabel.text = [NSString stringWithFormat:@"总计金额： %@元",_headerView.priceLabel.text];
    _totalRMBLabel.font = [UIFont systemFontOfSize:14];
    _totalRMBLabel.textColor = [UIColor orangeColor];
    [_centerView addSubview:_totalRMBLabel];
    
    _sureButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _sureButton.frame = CGRectMake(15, _totalRMBLabel.frame.origin.y + _totalRMBLabel.frame.size.height + 15, _centerView.frame.size.width - 30, 30);
    _sureButton.layer.borderWidth = 1;
    _sureButton.layer.borderColor = [UIColor orangeColor].CGColor;
    [_sureButton setTitle:@"确定" forState:UIControlStateNormal];
    _sureButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [_sureButton setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    [_sureButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    _sureButton.tag = 104;
    [_centerView addSubview:_sureButton];
}


- (void)buttonAction:(UIButton *)button {
    if (101 == button.tag) {
        _transprrentView.hidden = YES;
        _centerView.hidden = YES;
    }
    if (102 == button.tag) {
        if (_count > 1) {
            _count--;
           _numLabel.text = [NSString stringWithFormat:@"%d",_count];
        }
    }
    if (103 == button.tag) {
        _count++;
        _numLabel.text = [NSString stringWithFormat:@"%d",_count];
    }
    if (104 == button.tag) {
        SureDingdanViewController *sureVC = [[SureDingdanViewController alloc] init];
        // 属性传值
        // 截取字符串
        NSString *string = _headerView.priceLabel.text;
        NSRange range = [string rangeOfString:@"￥"];
        string = [string substringFromIndex:range.location + 1];
        sureVC.price = string;
        sureVC.postAge = _headerView.postLabel.text;
        sureVC.buyNumber = [_numLabel.text integerValue];
        sureVC.imageUrlString = _imageUrlStringArray[0];
        
        [self.navigationController pushViewController:sureVC animated:YES];
    }
}


// 区尾高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 50;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    _transprrentView.hidden = YES;
    _centerView.hidden = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
